package spring.module.zipfilter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import lombok.extern.slf4j.Slf4j;

/**
 * 过滤器
 *  
 * @author Lucky Yang
 */
@Slf4j
public class GZIPFilter implements Filter {
    private static final String CONTENT_ENCODING = "Content-Encoding";
    private static final String CONTENT_ENCODING_TYPE = "gzip";
        
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("init GZIPFilter");
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        long start = System.currentTimeMillis();
        HttpServletRequest httpRequest = (HttpServletRequest)request;

        String encodeType = httpRequest.getHeader(CONTENT_ENCODING);
        if (CONTENT_ENCODING_TYPE.equals(encodeType)) {
            log.info("请求:{} 需要解压", httpRequest.getRequestURI());
            UnZIPRequestWrapper unZIPRequestWrapper = new UnZIPRequestWrapper(httpRequest);
            chain.doFilter(unZIPRequestWrapper,response);
        }else {
            log.info("请求:{} 无需解压", httpRequest.getRequestURI());
            chain.doFilter(request,response);
        }
        log.info("耗时：{}ms", System.currentTimeMillis() - start);

    }

    @Override
    public void destroy() {
        log.info("destroy GZIPFilter");

        Filter.super.destroy();
    }
    
}
